//
//  ShowTopView.swift
//  DHLive
//
//  Created by Mac on 2021/6/30.
//

import UIKit

typealias TapBtnClosure = (_ tag: Int) -> ()

class ShowTopView: UIView {
    var tapBlock: TapBtnClosure?
    var lineView: UIView = UIView()
    var lineIndex: Int {
        set {
            UIView.animate(withDuration: 0.25) {
                self.lineView.center.x = self.btns[newValue].center.x
            }
        }
        get {0}
    }
    
    lazy var btns: [UIButton] = {
        [UIButton]()
    }()
    init(frame: CGRect, titles: Array<String>) {
        super.init(frame: frame)
        let width = frame.width / CGFloat(titles.count)
        for i in 0..<titles.count {
            let btn = UIButton(type: .custom)
            btns.append(btn)
            btn.setTitle(titles[i], for: .normal)
            btn.setTitleColor(.white, for: .normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 18)
            btn.frame = CGRect(x: width * CGFloat(i), y: 4, width: width, height: frame.height-8)
            btn.tag = i
            btn.addTarget(self, action: #selector(clickedTopView(btn:)), for: .touchUpInside)
            addSubview(btn)
            
            if i == 1 {
                btn.titleLabel?.sizeToFit()
                lineView = UIView()
                lineView.backgroundColor = .white
                
                lineView.frame.size.height = 2
                lineView.frame.size.width = btn.titleLabel?.frame.width ?? 0
                
                lineView.frame.origin.y = frame.height-6
                lineView.center.x = btn.center.x
                
                
                addSubview(lineView)
            }
        }
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


extension ShowTopView {
    @objc func clickedTopView(btn: UIButton) {
        if tapBlock != nil {
            tapBlock!(btn.tag)
        }
        UIView.animate(withDuration: 0.25) {
            self.lineView.center.x = btn.center.x
            self.lineView.frame.size.width = btn.titleLabel?.frame.width ?? 0
        }
        
    }
}
extension ShowTopView {
    func setLineView(offset: CGFloat, isRight: Bool) {
        print(offset, lineView.frame.origin.x, abs(offset - kScreenWidth))
        
        if isRight {
            lineView.frame.origin.x = lineView.frame.origin.x + offset / kScreenWidth
        }else {
            lineView.frame.origin.x = lineView.frame.origin.x - offset / kScreenWidth
        }
        
    }
    func setLineView(width: Int) {
        let btn = btns[width]
        lineView.frame.size.width = btn.titleLabel?.frame.width ?? 0
        lineView.center.x = btn.center.x
    }
}
